// 自定义实例默认值
import axios from "axios";

const isDev = process.env.NODE_ENV === 'development';

const myAxios = axios.create({
    // ✅ 生产环境使用相对路径，走 Nginx 代理
    baseURL: isDev ? "http://localhost:8080/api" : "/api",
});

// 允许携带 cookie
myAxios.defaults.withCredentials = true;

// 请求拦截器
myAxios.interceptors.request.use(
    (config) => {
        console.log("请求发送了", config);
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
myAxios.interceptors.response.use(
    (response) => {
        console.log("请求收到了", response);

        // 未登录跳转登录页
        if (response?.data?.code === 40100) {
            const redirectUrl = window.location.href;
            window.location.href = `/user/login?redirect=${redirectUrl}`;
        }

        return response.data;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default myAxios;